package com.endoc.agingtools.adapter;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.endoc.agingtools.FinalStaticString;
import com.endoc.agingtools.ItemBean;
import com.endoc.agingtools.R;
import com.endoc.agingtools.litepal.BindDevice;
import com.endoc.agingtools.utils.BleUtils;
import com.endoc.agingtools.view.PopupWindows;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class DeviceRecycleViewAdapter2 extends RecyclerView.Adapter<DeviceRecycleViewAdapter2.MyViewHolder>{
    String TAG = "DeviceRecycleViewAdapter";
    private Context context;
    private List<BleDevice> list = new ArrayList<>();//搜到数据除了已经绑定的数据集合
    private List<BleDevice> originalDeviceList;//原始搜到所有的数据
    boolean isBind =false;//是否有绑定的值
    private View inflater;
    RecyclerView mRecyclerView;
    ItemBean mItemBean;
    //构造方法，传入数据
    public DeviceRecycleViewAdapter2(Context context, ItemBean itemBean,List<BleDevice> list,RecyclerView recyclerView){
        this.context = context;
        originalDeviceList =list;
        mRecyclerView =recyclerView;
        mItemBean = itemBean;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //创建ViewHolder，返回每一项的布局
        inflater = LayoutInflater.from(context).inflate(R.layout.device_item,parent,false);
        MyViewHolder myViewHolder = new MyViewHolder(inflater);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        //Log.d(TAG,"position=="+position);

        //设置连接状态
        if(mItemBean.getDeviceName()!=null){
            holder.checkBox.setText(mItemBean.getDeviceName());
            holder.setButton.setText("解绑");
        }else {
            holder.checkBox.setText(list.get(position).getBleName());
            holder.setButton.setText("绑定");
        }

      /*  boolean isConnect = list.get(position).isConnected();
        holder.tvDeviceStatus.setText(isConnect?"连接":"断开");
        holder.tvDeviceStatus.setTextColor(isConnect? Color.parseColor("#FF5F51"):Color.parseColor("#323232"));*/

        //查看当前设备有没有被绑定
           /* if(isBind){
                holder.setButton.setText("解绑");
            }else {
                holder.setButton.setText("绑定");
            }*/

        holder.setButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(list.size()!=0){
                BleDevice bleDevice = list.get(position);
                BindDevice bindDevice =new BindDevice();
                bindDevice.setDeviceName(list.get(position).getBleName());//设置当前设备的名字
                Log.d(TAG,"当前button"+holder.setButton.getText().toString().trim());
                list.clear();
                if(holder.setButton.getText().toString().trim().equals("绑定")){
                    holder.setButton.setText("解绑");
                    bindDevice.setUser(true);//设置是否正在使用
                    bindDevice.setKawei(mItemBean.getKaiwei());
                    bindDevice.saveOrUpdate("deviceName = ?", bleDevice.getBleName());  //保存所有
                    //然后再设置只添加了当前集合的

                    list.add(bleDevice);
                    //isBind =true;
                    notifyDataSetChanged();

                    //连接
                    //BleUtils.connectDevice(bleDevice, DeviceRecycleViewAdapter2.this);
                   /* BleUtils.setAutoConnecrDevice(bleDevice, true);//并且设置自动连接*/

                    Log.d(TAG,"bind name=="+bleDevice.getBleName());
                }else if(holder.setButton.getText().toString().trim().equals("解绑")) {//否则是解绑
                    holder.setButton.setText("绑定");
                    //如果当前设备没有连接,那么就连接设备,并且将集合设置为当前
                    list.addAll(originalDeviceList);
                    bindDevice.setUser(false);
                    //保存所有
                    bindDevice.saveOrUpdate("deviceName = ?", bleDevice.getBleName());
                    //isBind =false;

                    notifyDataSetChanged();

                    //断开
                    if(bleDevice.isConnected()){
                        BleUtils.disConnecrDevice(bleDevice);
                    }
                   /* //并且取消自动连接,库中自动设置了
                    BleUtils.setAutoConnecrDevice(bleDevice,false);*/
                    Log.d(TAG,"unbind name=="+bleDevice.getBleName());

                }
                    //PopupWindows.getPopWnd(context,holder.itemView.getRootView().getRootView(),list.get(position),DeviceRecycleViewAdapter.this);
            } }
        });

       /* holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                //List<BindDevice> all = LitePal.findAll(BindDevice.class);

                //直接更新或者保存数据库中的数据
                BindDevice bindDevice =new BindDevice();
                bindDevice.setDeviceName(list.get(position).getBleName());//设置当前设备的名字
                bindDevice.setUser(isChecked);//设置是否正在使用
                bindDevice.saveOrUpdate("deviceName = ?", list.get(position).getBleName());

                if(isChecked){
                    if(!ischeckList.contains(position)) {
                        ischeckList.add(position);//如果选择了,那么添加到集合
                        Log.d(FinalStaticString.TAG, "checked=" + list.get(position).getBleName());
                        //bindDeviceList.add(list.get(position));
                        //执行连接操作
                        BleUtils.connectDevice(list.get(position), DeviceRecycleViewAdapter.this);
                        BleUtils.setAutoConnecrDevice(list.get(position), true);//并且设置自动连接

                    }
                }else {
                    ischeckList.remove((Integer) position);//否则移除集合
                    //bindDeviceList.remove(list.get(position));
                    //Log.d(FinalStaticString.TAG,"unchecked="+ bindDeviceList.size());
                    if(list.get(position).isConnected()){
                        BleUtils.disConnecrDevice(list.get(position));
                    }
                    //并且取消自动连接
                    BleUtils.setAutoConnecrDevice(list.get(position),false);
                }
            }
        });*/
    }


    @Override
    public int getItemCount() {
        list.clear();
        //如果当前卡位绑定了设备
        BindDevice bindDevice = LitePal.where("isUser = ? and deviceName = ?", "1", "" + mItemBean.getDeviceName()).findFirst(BindDevice.class);
        if(bindDevice!=null&&!bindDevice.getDeviceName().isEmpty()){
            //如果当前搜到的设备列表中包含卡位绑定的设备
            for(int i=0;i<originalDeviceList.size();i++){
                if(originalDeviceList.get(i).getBleName().equals(bindDevice.getDeviceName())){
                    list.add(originalDeviceList.get(i));
                }
            }
            //先查看
            return 1;
        }else {//否则显示所有搜到,除了被其他卡位绑定的的设备
            //返回Item总条数
            //查找当前数据库中已经绑定的设备
            List<BindDevice> bindDevices = LitePal.where("isUser = ?", "1").find(BindDevice.class);
            //添加集合数据
           list.addAll(originalDeviceList);
            for(int i=0;i<bindDevices.size();i++){
                //如果存在已经被其他卡位绑定的设备,那么就不显示了
               for(int j=0;j<list.size();j++){
                   //如果存在相同的数据
                   if(bindDevices.get(i).getDeviceName().equals(list.get(j).getBleName())&&!bindDevices.get(i).getDeviceName().equals(mItemBean.getDeviceName())){
                    //那么从列表中移除
                     list.remove(list.get(j));
                   }
               }
            }
            return list.size();
        }
    }

    //内部类，绑定控件
    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView checkBox;
         TextView tvDeviceStatus;
         Button setButton;
         public MyViewHolder(View itemView) {
            super(itemView);
            checkBox = (TextView) itemView.findViewById(R.id.tv_device_select);
            tvDeviceStatus = (TextView) itemView.findViewById(R.id.tv_device_status);
            setButton = (Button) itemView.findViewById(R.id.tv_device_set);
        }
    }
}

